package com.kele.single;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.LinkedList;

/**
 * @author kele
 * @date 2021/10/13 15:51
 * @description
 * 懒汉式单例
 */
public class LazySingle {

    private static boolean flag=false;


    private LazySingle(){
        if (flag==false){
            flag=true;
        }else {
            throw new RuntimeException("不要试图使用反射破环单例");
        }
//        synchronized (LazySingle.class){
//            if (lazySingle!=null){
//                throw new RuntimeException("不要试图使用反射破环单例");
//            }
//        }
    }
    private volatile static LazySingle lazySingle;

    /**
     * 并发条件下
     * 双重检索模式
     * @return
     */
    public  static LazySingle getInstance(){
        if (lazySingle==null){
            synchronized (LazySingle.class){
                if (lazySingle==null){
                    lazySingle=new LazySingle();
                }
            }

        }
        return lazySingle;
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //LazySingle single1 = LazySingle.getInstance();
//        Constructor<LazySingle> declaredConstructor = LazySingle.class.getDeclaredConstructor(null);
//        declaredConstructor.setAccessible(true);
//
//        LazySingle single2 = declaredConstructor.newInstance();
//        LazySingle single3 = declaredConstructor.newInstance();
//        System.out.println(single2==single3);

        String s = "tommy";
        Object o = s;
        sayHello(o); //语句1
        sayHello(s); //语句2
    }

    public static void sayHello(String to) {
        System.out.println(String.format("Hello, %s", to));
    }
    public static void sayHello(Object to) {
        System.out.println(String.format("Welcome, %s", to));
    }
}
